/**
 * 调用摄像头并截图上传模块
 **/
layui.define(function(exports) {
    var $ = layui.jquery
        ,MediaStreamTrack = {};
    if(navigator.userAgent.indexOf('Firefox') >= 0) {
        var is_ff = true;
    } else {
        var is_ff = false;
    }

    var obj = {
        aa:function() {
            console.log('aa');
        },
        start:function(video) {
            if(!is_ff) {
                layer.msg('请使用火狐浏览器尝试');
                return false;
            }
            //开启摄像头方法
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: false
                }).then(function (stream) {
                    MediaStreamTrack=typeof stream.stop==='function'?stream:stream.getTracks()[1];
                    //video.src=(window.URL).createObjectURL(stream);
                    video.srcObject  = stream;
                    video.play();
                }).catch(function(err){
                    console.log(err);
                    console.log('getUserMedia');
                    layer.msg('调起摄像头失败,请检查电脑驱动');
                });
            }else if(navigator.getMedia){
                navigator.getMedia({
                    video: true
                }).then(function (stream) {
                    MediaStreamTrack=stream.getTracks()[1];
                    video.src=(window.webkitURL).createObjectURL(stream);
                    video.play();
                }).catch(function(err){
                    console.log(err);
                    console.log('getMedia');
                    console.log('调起摄像头失败,请检查电脑驱动');
                });
            } else {
                layer.msg('不支持摄像头拍摄');
            }
        }
        ,snap:function(video,canvas ,loca,fun) {
            loca = loca || {one:0,two:0,three:200,four:150};
            //截图方法,可以进行其他后续操作,
            loca.one    = loca.one || 0;
            loca.two    = loca.two || 0;
            loca.three  = loca.three || 200;
            loca.four   = loca.four  || 150;

            if(fun) fun();
            $('#canvas_img').css('display','none');
            $('#canvas').css('display','block');
            var context = canvas.getContext('2d');
            context.drawImage(video, loca.one,loca.two,loca.three,loca.four);
        }
        ,close:function() {
            //关闭摄像头功能
            MediaStreamTrack && MediaStreamTrack.stop();
        }
        ,upload:function(url,sucess , fail,key) {
            sucess = sucess || false;
            fail = fail || false;
            key = key || 'base64';
            url = url || '/admin/upload/savebase64';
            //上传图片功能
            var obj = {};
            obj[key] = canvas.toDataURL('image/png');
            $.post(url, obj).done(sucess).fail(fail);
        }
    };

    //导出本接口
    exports('camera' , obj);
});